﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.AI
{
    public class TrafficCarTrigger : MonoBehaviour
    {

        public static Dictionary<Collider, TrafficCarTrigger> CarTriggerMap =
            new Dictionary<Collider, TrafficCarTrigger>(50);

        public BoxCollider triggerCollider;

        private List<ICarTriggerListener> _carTriggerListeners = new List<ICarTriggerListener>();

        private bool _greenState;
        
        public bool greenState
        {
            get => _greenState;
            set
            {
                _greenState = value;
                OnChangeState();
            }
        }
        private bool _yellowState;

        public bool yellowState
        {
            get => _yellowState;
            set
            {
                _yellowState = value;
                OnChangeState();
            }
        }
        
        //public bool redState => !greenState && !yellowState;

        public TrafficLightState lightState = TrafficLightState.Red;
        
        public void Awake()
        {
            if (triggerCollider!=null)
            {
                CarTriggerMap[triggerCollider] = this;
            }
        }

        private void OnChangeState()
        {
            if (greenState)
            {
                lightState = TrafficLightState.Green;
            }
            else if (yellowState)
            {
                lightState = TrafficLightState.Yellow;
            }
            else
            {
                lightState = TrafficLightState.Red;
            }


            foreach (var triggerListener in _carTriggerListeners)
            {
                triggerListener.OnChangeState(lightState);
            }
        }

        public void AddTriggerListener(ICarTriggerListener triggerListener)
        {
            if (!_carTriggerListeners.Contains(triggerListener))
            {
                _carTriggerListeners.Add(triggerListener);
            }
        }

        public void RemoveTriggerListener(ICarTriggerListener triggerListener)
        {            
            if (!_carTriggerListeners.Contains(triggerListener)) return;
            _carTriggerListeners.Remove(triggerListener);
        }
        
    }
}